package com.rcl.recyclerviewdemo.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.rcl.recyclerviewdemo.R;
import com.rcl.recyclerviewdemo.bean.ContentBean;

import java.util.ArrayList;
import java.util.List;

/*
 * class title:
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2020/11/3.
 * PS: Not easy to write code, please indicate.
 */
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {

    private List<ContentBean> mList = new ArrayList<>();
    private List<Integer> mHeights = new ArrayList<>();

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_home, parent, false);
        ViewHolder viewHolder = new ViewHolder(inflate);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ContentBean contentBean = mList.get(position);
        holder.content.setText(contentBean.getContent());
        ViewGroup.LayoutParams layoutParams = holder.content.getLayoutParams();
        layoutParams.height = mHeights.get(position);
        holder.content.setLayoutParams(layoutParams);
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public void setData(List<ContentBean> contentBean) {
        mList.clear();
        mList.addAll(contentBean);
        for (ContentBean bean : mList) {
            mHeights.add((int) (100 + Math.random() * 300));
        }
        notifyDataSetChanged();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView content;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            content = itemView.findViewById(R.id.tv_content);
        }
    }

    //添加和删除的动画
    public void addData(int position) {
        ContentBean contentBean = new ContentBean();
        contentBean.setContent("New Item");
        mList.add(position, contentBean);
        notifyItemInserted(position);
    }

    public void removeData(int position) {
        mList.remove(position);
        notifyItemRemoved(position);
    }
}
